﻿#region Copyright RenGuiYou. All rights reserved.
//=====================================================
// NeatlyFrameWork
// Author:      RenGuiyou
// Feedback: 	mailto:750539605@qq.com
//=====================================================
#endregion
using System.Collections.Generic;
using System.IO;
using Pandora;
using PandoraEditor;
using UnityEditor;
using UnityEngine;

namespace NeatlyEditor
{
    public static class AssetBundleImport
    {
        private const string DIR_ASSETS_BUNDLE_MAP = "Assets/AssetBundleMap";
        private const string PATH_ASSETS_BUNDLE_MAP = "Assets/AssetBundleMap/assetbundlemap.asset";
        static readonly Dictionary<string, string> m_DicBundleMap = new();
        public static readonly Dictionary<string, List<string>> m_BuildAssetMap = new();

        //初始化
        public static void Init()
        {
            m_DicBundleMap.Clear();
            m_BuildAssetMap.Clear();
        }

        #region AssetBundle映射表
        //获取,创建 AssetBundleMap
        private static AssetBundleMap GetAssetBundleMap()
        {
            if (!Directory.Exists(DIR_ASSETS_BUNDLE_MAP))
            {
                PdrFileUtil.CreateDirectory(DIR_ASSETS_BUNDLE_MAP);
                AssetDatabase.Refresh();
            }
            if (!File.Exists(PATH_ASSETS_BUNDLE_MAP))
            {
                AssetDatabase.Refresh();
                var scriptableObj = ScriptableObject.CreateInstance<AssetBundleMap>();
                AssetDatabase.CreateAsset(scriptableObj, PATH_ASSETS_BUNDLE_MAP);
                AssetDatabase.SaveAssets();
                AssetDatabase.Refresh();
                return scriptableObj;
            }
            return AssetDatabase.LoadAssetAtPath<AssetBundleMap>(PATH_ASSETS_BUNDLE_MAP);
        }

        //检测是否更新
        public static bool CheckRefreshBundleMap(AssetBundleMap map)
        {
            if (map.path == null || map.bundleName == null) return true;
            var length = map.path.Length;
            if (m_DicBundleMap.Count != length)
                return true;
            for (int i = 0; i < length; i++)
            {
                var key = map.path[i];
                m_DicBundleMap.TryGetValue(key, out var dicValue);
                if (dicValue != map.bundleName[i])
                {
                    return true;
                }
            }
            return false;
        }

        //写入bundle映射
        public static void WriteBundlePathNameMap()
        {
            var bundleMap = GetAssetBundleMap();
            var needRefresh = CheckRefreshBundleMap(bundleMap);
            if (needRefresh)
            {
                int length = m_DicBundleMap.Count;
                bundleMap.path = new string[length];
                bundleMap.bundleName = new string[length];
                int index = 0;
                foreach (var kv in m_DicBundleMap)
                {
                    bundleMap.path[index] = kv.Key;
                    bundleMap.bundleName[index] = kv.Value;
                    index++;
                }
            }
            EditorUtility.SetDirty(bundleMap);
            AssetDatabase.SaveAssets();
            AssetDatabase.Refresh();
            //设置AssetBundleMap的bundle信息
            ImportSingle(PATH_ASSETS_BUNDLE_MAP, NeatlyConfig.NAME_ASSET_BUNDLE_MAP);
            m_DicBundleMap.Clear();
        }

        //清理bundleName
        public static void ClearBundleName()
        {
            var names = AssetDatabase.GetAllAssetBundleNames();
            foreach (string name in names)
            {
                AssetDatabase.RemoveAssetBundleName(name, true);
            }
        }
        #endregion
        #region 导入Lua
        public static void ExportLua()
        {
            ImportSingle(GetFullAssetsPath("lua32"), null, false);
            ImportSingle(GetFullAssetsPath("lua64"), null, false);
        }
        #endregion
        #region 导入图集
        public static void ExportAtlas()
        {
            string fullPath = GetFullAssetsPath(NeatlyConfig.PATH_ATLAS_TP);
            List<string> fileList = PdrFileUtil.GetFilesName(fullPath, ".prefab");
            foreach (var file in fileList)
            {
                string filePath = RemoveAssetsRoot(file).SubstringTo(".");
                string bundleName = FormatBundleNameByPath(filePath);
                ImportSingle(PdrCombine.Prefab(filePath), bundleName);
                ImportSingle(PdrCombine.Material(filePath), bundleName, false);
                ImportSingle(PdrCombine.PngColor(filePath), bundleName, false);
                string blurMaterialPath = PdrCombine.BlurMaterial(filePath);
                if (File.Exists(blurMaterialPath))
                {
                    ImportSingle(blurMaterialPath, bundleName, false);
                }
            }
            ImportSingle(NeatlyConfig.PATH_FILE_ATLAS_CONFIG);
        }
        #endregion
        #region 导入UIPanel
        public static void ExportUIPanel()
        {
            ImportMultiCatalog(NeatlyConfig.PATH_UI_PANEL);
        }
        #endregion
        #region 导入声音
        public static void ExportMusic()
        {
            string fullPath = GetFullAssetsPath($"data/{NeatlyConfig.MUSIC_PACKAGE}");
            List<string> fileList = PdrFileUtil.GetFilesName(fullPath, NeatlyConfig.SUFFIX_MUSIC);
            foreach (var filePath in fileList)
            {
                string bundleName = filePath.GetFileName().SubstringTo(".");
                ImportSingle(filePath, $"music_{bundleName}", false);
            }
        }

        public static void ExportSound()
        {
            string path = $"data/{NeatlyConfig.SOUND_PACKAGE}";
            ImportSingle(path, NeatlyConfig.SOUND_PACKAGE);
        }

        public static void ExportVoice()
        {
            string path = $"data/{NeatlyConfig.VOICE_PACKAGE}";
            ImportSingle(path, NeatlyConfig.VOICE_PACKAGE);
        }

        public static void ExportVideo()
        {
            string path = $"data/{NeatlyConfig.VIDEO_PACKAGE}";
            ImportSingle(path, NeatlyConfig.VIDEO_PACKAGE);
        }
        #endregion
        #region 导入场景
        public static void ExportScene()
        {
            string fullPath = NeatlyEditorConfig.PATH_SCENE_OFFICIAL;
            if (!Directory.Exists(fullPath))
            {
                return;
            }
            List<string> fileList = PdrFileUtil.GetFilesName(fullPath, ".unity");
            foreach (var filePath in fileList)
            {
                string bundleName = filePath.GetFileName().SubstringTo(".");
                ImportSingle(filePath, $"scene_{bundleName}", false);
            }
        }
        #endregion
        #region 导入基础
        //导入所有文件
        public static void ImportMultiFile(string path)
        {
            string fullPath = GetFullAssetsPath(path);
            var dirChildren = PdrFileUtil.GetFilesName(fullPath);
            foreach (var v in dirChildren)
            {
                ImportSingle(v);
            }
        }

        //导入所有子文件夹
        public static void ImportMultiCatalog(string path)
        {
            string fullPath = GetFullAssetsPath(path);
            DirectoryInfo dirInfo = new DirectoryInfo(fullPath);
            var dirChildren = dirInfo.GetDirectories();
            foreach (var v in dirChildren)
            {
                ImportSingle(Path.Combine(path, v.Name));
            }
        }

        //导入单个文件or单个目录
        public static void ImportSingle(string fullPath, string bundleName = null, bool importMap = true)
        {
            fullPath = GetFullAssetsPath(fullPath);
            if (string.IsNullOrEmpty(bundleName))
                bundleName = FormatBundleNameByPath(fullPath);
            //为目录时所有子成员加入
            if (Directory.Exists(fullPath))
            {
                var childFiles = PdrFileUtil.GetFilesName(fullPath);
                foreach (var t in childFiles)
                {
                    ImportSingleBase(t, bundleName, importMap);
                }
            }
            else
            {
                ImportSingleBase(fullPath, bundleName, importMap);
            }
        }

        //导入bundleName
        private static void ImportSingleBase(string fullPath, string bundleName, bool importMap = true)
        {
            fullPath = GetFullAssetsPath(fullPath);
            if (importMap)
            {
                m_DicBundleMap.Add(FormatBundleMapKey(fullPath), bundleName);
            }
            m_BuildAssetMap.TryGetValue(bundleName, out var assetList);
            if (assetList == null)
            {
                assetList = new List<string>();
                m_BuildAssetMap.Add(bundleName, assetList);
            }
            assetList.Add(fullPath);
        }
        #endregion
        #region Misc
        //格式化成AssetBundleMap的key
        private static string FormatBundleMapKey(string path)
        {
            return RemoveAssetsRoot(path.StandardPath()).SubstringTo(".");
        }

        //去掉(assets/)
        private static string RemoveAssetsRoot(string source)
        {
            return source.ReplacePath("assets/", "");
        }

        //路径Combine assets
        private static string GetFullAssetsPath(string path)
        {
            path = path.ToLower();
            path = path.Replace("\\", "/");
            return path.StartsWith("assets/") ? path : Path.Combine("assets", path);
        }

        //格式化bundleName
        private static string FormatBundleNameByPath(string path)
        {
            string name = path.StandardPath();
            name = name.ReplaceEmpty("assets/");
            return name.Replace("/", "_").SubstringTo(".");
        }
        #endregion
    }
}